<!DOCTYPE html>


<html theme="dark" showBanner="true" hasBanner="false" > 
<link href="https://cdn.staticfile.org/font-awesome/6.4.2/css/fontawesome.min.css" rel="stylesheet">
<link href="https://cdn.staticfile.org/font-awesome/6.4.2/css/brands.min.css" rel="stylesheet">
<link href="https://cdn.staticfile.org/font-awesome/6.4.2/css/solid.min.css" rel="stylesheet">
<script src="/hexo-blog/js/color.global.min.js" ></script>
<script src="/hexo-blog/js/load-settings.js" ></script>
<head>
  <meta charset="utf-8">
  
  
  

  
  <title>React 关于ref，你想知道的都在这里 | bressanone</title>
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

  <link rel="preload" href="/hexo-blog/css/fonts/Roboto-Regular.ttf" as="font" type="font/ttf" crossorigin="anonymous">
  <link rel="preload" href="/hexo-blog/css/fonts/Roboto-Bold.ttf" as="font" type="font/ttf" crossorigin="anonymous">

  <meta name="description" content="这是我参与11月更文挑战的第23天，活动详情查看：2021最后一次更文挑战 ref属性可以传哪些值React.createRef()、React.useRef()创建的对象；回调函数、字符串  此属性可以是一个由 React.createRef() 函数创建的对象、或者一个回调函数、或者一个字符串（遗留 API）。当 ref 属性是一个回调函数时，此函数会（根据元素的类型）接收底层 DOM 元素或">
<meta property="og:type" content="article">
<meta property="og:title" content="React 关于ref，你想知道的都在这里">
<meta property="og:url" content="http://example.com/2021/11/23/React%20%E5%85%B3%E4%BA%8Eref%EF%BC%8C%E4%BD%A0%E6%83%B3%E7%9F%A5%E9%81%93%E7%9A%84%E9%83%BD%E5%9C%A8%E8%BF%99%E9%87%8C/index.html">
<meta property="og:site_name" content="bressanone">
<meta property="og:description" content="这是我参与11月更文挑战的第23天，活动详情查看：2021最后一次更文挑战 ref属性可以传哪些值React.createRef()、React.useRef()创建的对象；回调函数、字符串  此属性可以是一个由 React.createRef() 函数创建的对象、或者一个回调函数、或者一个字符串（遗留 API）。当 ref 属性是一个回调函数时，此函数会（根据元素的类型）接收底层 DOM 元素或">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://example.com/2021/11/23/imgs/ce724a5dffb94210bc95e6efedaef78d.png">
<meta property="og:image" content="http://example.com/2021/11/23/imgs/81a67e5d708a4e75af8b9a9fc7c2d317.png">
<meta property="og:image" content="http://example.com/2021/11/23/imgs/c3e1ac10e91f4a249046400414dd795c.png">
<meta property="article:published_time" content="2021-11-22T16:00:00.000Z">
<meta property="article:modified_time" content="2024-04-13T12:20:29.581Z">
<meta property="article:author" content="Zachary">
<meta property="article:tag" content="前端">
<meta property="article:tag" content="React.js">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2021/11/23/imgs/ce724a5dffb94210bc95e6efedaef78d.png">
  
  
    <link rel="icon" media="(prefers-color-scheme: light)" href="/hexo-blog/images/favicon-light-32.png" sizes="32x32">
    <link rel="icon" media="(prefers-color-scheme: light)" href="/hexo-blog/images/favicon-light-128.png" sizes="128x128">
    <link rel="icon" media="(prefers-color-scheme: light)" href="/hexo-blog/images/favicon-light-180.png" sizes="180x180">
    <link rel="icon" media="(prefers-color-scheme: light)" href="/hexo-blog/images/favicon-light-192.png" sizes="192x192">
    <link rel="icon" media="(prefers-color-scheme: dark)" href="/hexo-blog/images/favicon-dark-32.png" sizes="32x32">
    <link rel="icon" media="(prefers-color-scheme: dark)" href="/hexo-blog/images/favicon-dark-128.png" sizes="128x128">
    <link rel="icon" media="(prefers-color-scheme: dark)" href="/hexo-blog/images/favicon-dark-180.png" sizes="180x180">
    <link rel="icon" media="(prefers-color-scheme: dark)" href="/hexo-blog/images/favicon-dark-192.png" sizes="192x192">
  
  
<link rel="stylesheet" href="/hexo-blog/css/style.css">

<meta name="generator" content="Hexo 7.1.1"></head>

<body>
  
   
  <div id="main-grid" class="  ">
    <div id="nav" class=""  >
      <navbar id="navbar">
  <nav id="title-nav">
    <a href="/hexo-blog/">
      <div id="vivia-logo">
        <div class="dot"></div>
        <div class="dot"></div>
        <div class="dot"></div>
        <div class="dot"></div>
      </div>
      <div>bressanone </div>
    </a>
  </nav>
  <nav id="main-nav">
    
      <a class="main-nav-link" href="/hexo-blog/">主页</a>
    
      <a class="main-nav-link" href="/hexo-blog/archives">归档</a>
    
      <a class="main-nav-link" href="/hexo-blog/about">关于</a>
    
  </nav>
  <nav id="sub-nav">
    <a id="theme-btn" class="nav-icon">
      <span class="light-mode-icon"><svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="M438.5-829.913v-48q0-17.452 11.963-29.476 11.964-12.024 29.326-12.024 17.363 0 29.537 12.024t12.174 29.476v48q0 17.452-11.963 29.476-11.964 12.024-29.326 12.024-17.363 0-29.537-12.024T438.5-829.913Zm0 747.826v-48q0-17.452 11.963-29.476 11.964-12.024 29.326-12.024 17.363 0 29.537 12.024t12.174 29.476v48q0 17.452-11.963 29.476-11.964 12.024-29.326 12.024-17.363 0-29.537-12.024T438.5-82.087ZM877.913-438.5h-48q-17.452 0-29.476-11.963-12.024-11.964-12.024-29.326 0-17.363 12.024-29.537t29.476-12.174h48q17.452 0 29.476 11.963 12.024 11.964 12.024 29.326 0 17.363-12.024 29.537T877.913-438.5Zm-747.826 0h-48q-17.452 0-29.476-11.963-12.024-11.964-12.024-29.326 0-17.363 12.024-29.537T82.087-521.5h48q17.452 0 29.476 11.963 12.024 11.964 12.024 29.326 0 17.363-12.024 29.537T130.087-438.5Zm660.174-290.87-34.239 32q-12.913 12.674-29.565 12.174-16.653-.5-29.327-13.174-12.674-12.673-12.554-28.826.12-16.152 12.794-28.826l33-35q12.913-12.674 30.454-12.674t30.163 12.847q12.709 12.846 12.328 30.826-.38 17.98-13.054 30.653ZM262.63-203.978l-32 34q-12.913 12.674-30.454 12.674t-30.163-12.847q-12.709-12.846-12.328-30.826.38-17.98 13.054-30.653l33.239-31q12.913-12.674 29.565-12.174 16.653.5 29.327 13.174 12.674 12.673 12.554 28.826-.12 16.152-12.794 28.826Zm466.74 33.239-32-33.239q-12.674-12.913-12.174-29.565.5-16.653 13.174-29.327 12.673-12.674 28.826-13.054 16.152-.38 28.826 12.294l35 33q12.674 12.913 12.674 30.454t-12.847 30.163q-12.846 12.709-30.826 12.328-17.98-.38-30.653-13.054ZM203.978-697.37l-34-33q-12.674-12.913-13.174-29.945-.5-17.033 12.174-29.707t31.326-13.293q18.653-.62 31.326 13.054l32 34.239q11.674 12.913 11.174 29.565-.5 16.653-13.174 29.327-12.673 12.674-28.826 12.554-16.152-.12-28.826-12.794ZM480-240q-100 0-170-70t-70-170q0-100 70-170t170-70q100 0 170 70t70 170q0 100-70 170t-170 70Zm-.247-82q65.703 0 111.475-46.272Q637-414.544 637-480.247t-45.525-111.228Q545.95-637 480.247-637t-111.475 45.525Q323-545.95 323-480.247t45.525 111.975Q414.05-322 479.753-322ZM481-481Z"/></svg></span>
      <span class="dark-mode-icon"><svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="M480.239-116.413q-152.63 0-258.228-105.478Q116.413-327.37 116.413-480q0-130.935 77.739-227.435t206.304-125.043q43.022-9.631 63.87 10.869t3.478 62.805q-8.891 22.043-14.315 44.463-5.424 22.42-5.424 46.689 0 91.694 64.326 155.879 64.325 64.186 156.218 64.186 24.369 0 46.978-4.946 22.609-4.945 44.413-14.076 42.826-17.369 62.967 1.142 20.142 18.511 10.511 61.054Q807.174-280 712.63-198.206q-94.543 81.793-232.391 81.793Zm0-95q79.783 0 143.337-40.217 63.554-40.218 95.793-108.283-15.608 4.044-31.097 5.326-15.49 1.283-31.859.805-123.706-4.066-210.777-90.539-87.071-86.473-91.614-212.092-.24-16.369.923-31.978 1.164-15.609 5.446-30.978-67.826 32.478-108.282 96.152Q211.652-559.543 211.652-480q0 111.929 78.329 190.258 78.329 78.329 190.258 78.329ZM466.13-465.891Z"/></svg></span>
    </a>
    
    <div id="nav-menu-btn" class="nav-icon">
      <svg xmlns="http://www.w3.org/2000/svg" height="20" viewBox="0 -960 960 960" width="20"><path d="M177.37-252.282q-17.453 0-29.477-11.964-12.024-11.963-12.024-29.326t12.024-29.537q12.024-12.174 29.477-12.174h605.26q17.453 0 29.477 11.964 12.024 11.963 12.024 29.326t-12.024 29.537q-12.024 12.174-29.477 12.174H177.37Zm0-186.218q-17.453 0-29.477-11.963-12.024-11.964-12.024-29.326 0-17.363 12.024-29.537T177.37-521.5h605.26q17.453 0 29.477 11.963 12.024 11.964 12.024 29.326 0 17.363-12.024 29.537T782.63-438.5H177.37Zm0-186.217q-17.453 0-29.477-11.964-12.024-11.963-12.024-29.326t12.024-29.537q12.024-12.174 29.477-12.174h605.26q17.453 0 29.477 11.964 12.024 11.963 12.024 29.326t-12.024 29.537q-12.024 12.174-29.477 12.174H177.37Z"/></svg>
    </div>
  </nav>
</navbar>
<div id="nav-dropdown" class="hidden">
  <div id="dropdown-link-list">
    
      <a class="nav-dropdown-link" href="/hexo-blog/">主页</a>
    
      <a class="nav-dropdown-link" href="/hexo-blog/archives">归档</a>
    
      <a class="nav-dropdown-link" href="/hexo-blog/about">关于</a>
    
     
    </div>
</div>
<script>
  let dropdownBtn = document.getElementById("nav-menu-btn");
  let dropdownEle = document.getElementById("nav-dropdown");
  dropdownBtn.onclick = function() {
    dropdownEle.classList.toggle("hidden");
  }
</script>
    </div>
    <div id="sidebar-wrapper">
      <sidebar id="sidebar">
  
    <div class="widget-wrap">
  <div class="info-card">
    <div class="avatar">
      
      <div class="img-dim"></div>
    </div>
    <div class="info">
      <div class="username">Zachary </div>
      <div class="dot"></div>
      <div class="subtitle"> </div>
      <div class="link-list">
        
          <a class="link-btn" target="_blank" rel="noopener" href="https://github.com/zzy1661" title="GitHub"><i class="fa-brands fa-github"></i></a>
         
      </div>  
    </div>
  </div>
</div>

  
  <div class="sticky">
    
      


  <div class="widget-wrap">
    <div class="widget">
      <h3 class="widget-title">分类</h3>
      <div class="category-box">
            <a class="category-link" href="/hexo-blog/categories/%E5%89%8D%E7%AB%AF%E7%AC%94%E8%AE%B0/">
                前端笔记
                <div class="category-count">78</div>
            </a>
        
            <a class="category-link" href="/hexo-blog/categories/%E7%AE%97%E6%B3%95%E6%89%8B%E5%86%8C/">
                算法手册
                <div class="category-count">7</div>
            </a>
        </div>
    </div>
  </div>


    
      
  <div class="widget-wrap">
    <div class="widget">
      <h3 class="widget-title">标签</h3>
      <ul class="widget-tag-list" itemprop="keywords"><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Ant-Design/" rel="tag">Ant Design</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/CSS/" rel="tag">CSS</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Canvas/" rel="tag">Canvas</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Docker/" rel="tag">Docker</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/ECMAScript-6/" rel="tag">ECMAScript 6</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/JavaScript/" rel="tag">JavaScript</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Less/" rel="tag">Less</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/MobX/" rel="tag">MobX</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/MongoDB/" rel="tag">MongoDB</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/NPM/" rel="tag">NPM</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/NestJS/" rel="tag">NestJS</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Node-js/" rel="tag">Node.js</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Postman/" rel="tag">Postman</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/React-js/" rel="tag">React.js</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Redux/" rel="tag">Redux</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/TypeScript/" rel="tag">TypeScript</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/UML/" rel="tag">UML</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Webpack/" rel="tag">Webpack</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/Yeoman/" rel="tag">Yeoman</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/%E5%89%8D%E7%AB%AF/" rel="tag">前端</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/%E6%9E%B6%E6%9E%84/" rel="tag">架构</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" rel="tag">正则表达式</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/%E6%BA%90%E7%A0%81/" rel="tag">源码</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/%E7%88%AC%E8%99%AB/" rel="tag">爬虫</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/%E7%AE%97%E6%B3%95/" rel="tag">算法</a></li><li class="widget-tag-list-item"><a class="widget-tag-list-link" href="/hexo-blog/tags/%E9%9D%A2%E8%AF%95/" rel="tag">面试</a></li></ul>
    </div>
  </div>


    
  </div>
</sidebar>
    </div>
    <div id="content-body">
       


<article id="post-React 关于ref，你想知道的都在这里" class="h-entry article article-type-post" itemprop="blogPost" itemscope itemtype="https://schema.org/BlogPosting">
  
    
   
  <div class="article-inner">
    <div class="article-main">
      <header class="article-header">
        
<div class="main-title-bar">
  <div class="main-title-dot"></div>
  
    
      <h1 class="p-name article-title" itemprop="headline name">
        React 关于ref，你想知道的都在这里
      </h1>
    
  
</div>

        <div class='meta-info-bar'>
          <div class="meta-info">
  <time class="dt-published" datetime="2021-11-22T16:00:00.000Z" itemprop="datePublished">2021-11-23</time>
</div>
          <div class="need-seperator meta-info">
            <div class="meta-cate-flex">
  
  <a class="meta-cate-link" href="/hexo-blog/categories/%E5%89%8D%E7%AB%AF%E7%AC%94%E8%AE%B0/">前端笔记</a>
   
</div>
  
          </div>
          <div class="wordcount need-seperator meta-info">
            5.2k 词 
          </div>
        </div>
        
  <ul class="article-tag-list" itemprop="keywords"><li class="article-tag-list-item"><a class="article-tag-list-link" href="/hexo-blog/tags/React-js/" rel="tag">React.js</a></li><li class="article-tag-list-item"><a class="article-tag-list-link" href="/hexo-blog/tags/%E5%89%8D%E7%AB%AF/" rel="tag">前端</a></li></ul>

      </header>
      <div class="e-content article-entry" itemprop="articleBody">
        
          <p>这是我参与11月更文挑战的第23天，活动详情查看：<a target="_blank" rel="noopener" href="https://juejin.cn/post/7023643374569816095" title="https://juejin.cn/post/7023643374569816095">2021最后一次更文挑战</a></p>
<h2 id="ref属性可以传哪些值"><a href="#ref属性可以传哪些值" class="headerlink" title="ref属性可以传哪些值"></a>ref属性可以传哪些值</h2><p>React.createRef()、React.useRef()创建的对象；回调函数、字符串</p>
<blockquote>
<p>此属性可以是一个由 <a href="https://zh-hans.reactjs.org%2Fdocs%2Freact-api.html%23reactcreateref" title="https://zh-hans.reactjs.org/docs/react-api.html#reactcreateref"><code>React.createRef()</code> 函数</a>创建的对象、或者一个回调函数、或者一个字符串（遗留 API）。当 <code>ref</code> 属性是一个回调函数时，此函数会（根据元素的类型）接收底层 DOM 元素或 class 实例作为其参数。这能够让你直接访问 DOM 元素或组件实例。</p>
</blockquote>
<h2 id="字符串refs"><a href="#字符串refs" class="headerlink" title="字符串refs"></a>字符串refs</h2><p>曾经字符串refs在class component中比较流行，但是现在，传字符串的用法已经过时了</p>
<blockquote>
<p>我们不建议使用它，因为 string 类型的 refs 存在 <a href="https://github.com%2Ffacebook%2Freact%2Fpull%2F8333%23issuecomment-271648615" title="https://github.com/facebook/react/pull/8333#issuecomment-271648615">一些问题</a>。它已过时并可能会在未来的版本被移除。</p>
</blockquote>
<h2 id="回调refs"><a href="#回调refs" class="headerlink" title="回调refs"></a>回调refs</h2><figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line">export default function IndexPage() &#123;</span><br><span class="line">  const <span class="section">[count, setCount]</span> = useState(0)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">  const <span class="attr">add</span> = useCallback(() =&gt; &#123;</span><br><span class="line">    setCount((count) =&gt; &#123;</span><br><span class="line">      return ++count<span class="comment">;</span></span><br><span class="line">    &#125;)<span class="comment">;</span></span><br><span class="line">  &#125;, <span class="section">[]</span>)<span class="comment">;</span></span><br><span class="line"></span><br><span class="line">  return (</span><br><span class="line">    &lt;div <span class="attr">className</span>=<span class="string">&quot; p-12&quot;</span>&gt;</span><br><span class="line">      &lt;div&gt;callback refs &lt;/div&gt;</span><br><span class="line">      &lt;div <span class="attr">className</span>=<span class="string">&quot;w-32 inline-block mr-2&quot;</span>&gt;</span><br><span class="line">        &lt;Input <span class="attr">value</span>=&#123;count&#125;&gt;&lt;/Input&gt;</span><br><span class="line">      &lt;/div&gt;</span><br><span class="line">      &lt;Button</span><br><span class="line">        <span class="attr">ref</span>=&#123;(dom)=&gt;console.log(dom)&#125;</span><br><span class="line">        <span class="attr">icon</span>=&#123;&lt;PlusOutlined /&gt;&#125;</span><br><span class="line">        <span class="attr">className</span>=<span class="string">&quot;ml-8&quot;</span></span><br><span class="line">        <span class="attr">onClick</span>=&#123;add&#125;</span><br><span class="line">      &gt;</span><br><span class="line">        add</span><br><span class="line">      &lt;/Button&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">  )<span class="comment">;</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>React 将在组件挂载时，会调用 <code>ref</code> 回调函数并传入 DOM 元素，当卸载时调用它并传入 <code>null</code>。在 <code>componentDidMount</code> 或 <code>componentDidUpdate</code> 触发前，React 会保证 refs 一定是最新的。</p>
<p>另外，组件的每一次更新都会调用这个callback两次，第一次传入null：</p>
<p><img src="./../imgs/ce724a5dffb94210bc95e6efedaef78d.png" alt="image.png"></p>
<h2 id="createRef与useRef"><a href="#createRef与useRef" class="headerlink" title="createRef与useRef"></a>createRef与useRef</h2><h3 id="定义："><a href="#定义：" class="headerlink" title="定义："></a>定义：</h3><ul>
<li>createRef:<code>React.createRef</code> 创建一个能够通过 ref 属性附加到 React 元素的 <a href="https://zh-hans.reactjs.org%2Fdocs%2Frefs-and-the-dom.html" title="https://zh-hans.reactjs.org/docs/refs-and-the-dom.html">ref</a>。</li>
<li>useRef: <code>useRef</code>：简单理解就是返回了一个ref对象，拥有<code>current</code>属性。</li>
</ul>
<blockquote>
<p>useRef返回一个可变的 ref 对象，其 <code>.current</code> 属性被初始化为传入的参数（<code>initialValue</code>）。返回的 ref 对象在组件的整个生命周期内持续存在。</p>
</blockquote>
<p>虽然两者都能够传给ref，并获取到dom，但是我们来看一下区别：</p>
<h3 id="区别"><a href="#区别" class="headerlink" title="区别"></a>区别</h3><ul>
<li>语法区别 createRef是不可以传入初始值的，current属性也是只读的。而useRef不是。</li>
<li>底层区别 首先维护两个set</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">export</span> <span class="keyword">const</span>  uRefs = <span class="keyword">new</span> <span class="title class_">Set</span>()</span><br><span class="line"><span class="keyword">export</span> <span class="keyword">const</span> cRefs = <span class="keyword">new</span> <span class="title class_">Set</span>()</span><br></pre></td></tr></table></figure>

<p>每次更新都将useRef和createRef创建的对象分别放入这两个set:</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> &#123; uRefs, cRefs &#125; <span class="keyword">from</span> <span class="string">&#x27;./data&#x27;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">export</span> <span class="keyword">default</span> <span class="keyword">function</span> <span class="title function_">IndexPage</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = <span class="title function_">useState</span>(<span class="number">0</span>);</span><br><span class="line">  <span class="keyword">const</span> uRef = useRef&lt;<span class="built_in">any</span>&gt;();</span><br><span class="line">  <span class="keyword">const</span> cRef = createRef&lt;<span class="built_in">any</span>&gt;();</span><br><span class="line">  <span class="keyword">const</span> uRef1 = <span class="title function_">useRef</span>(<span class="number">0</span>);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> cRef1 = <span class="title function_">createRef</span>();</span><br><span class="line">  <span class="keyword">const</span> add = <span class="title function_">useCallback</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="title function_">setCount</span>(<span class="function">(<span class="params">count</span>) =&gt;</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> ++count;</span><br><span class="line">    &#125;);</span><br><span class="line">  &#125;, []);</span><br><span class="line">  <span class="title function_">useEffect</span>(<span class="function">() =&gt;</span> &#123;</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;update&#x27;</span>)</span><br><span class="line">    uRefs.<span class="title function_">add</span>(uRef);</span><br><span class="line">    cRefs.<span class="title function_">add</span>(cRef)</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;uRef&#x27;</span>, uRefs)</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&#x27;cRef&#x27;</span>, cRefs)</span><br><span class="line">  &#125;);</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&quot; p-12&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span>&gt;</span>createRef 与 useRef <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&quot;w-32 inline-block mr-2&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        use ref ：<span class="tag">&lt;<span class="name">Input</span> <span class="attr">ref</span>=<span class="string">&#123;uRef&#125;</span> <span class="attr">value</span>=<span class="string">&#123;count&#125;</span>&gt;</span><span class="tag">&lt;/<span class="name">Input</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&quot;w-32 inline-block&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        create ref: <span class="tag">&lt;<span class="name">Input</span> <span class="attr">ref</span>=<span class="string">&#123;cRef&#125;</span> <span class="attr">value</span>=<span class="string">&#123;count&#125;</span>&gt;</span><span class="tag">&lt;/<span class="name">Input</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">Button</span>  <span class="attr">icon</span>=<span class="string">&#123;</span>&lt;<span class="attr">PlusOutlined</span> /&gt;</span>&#125;  className=&quot;ml-8&quot; onClick=&#123;add&#125;&gt;</span></span><br><span class="line"><span class="language-xml">        add</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">Button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>经历两次更新后： <img src="./../imgs/81a67e5d708a4e75af8b9a9fc7c2d317.png" alt="image.png"> 可以看到，每次更新，createRef都会重新创建一次ref对象，并将老的ref对象的current置位null;</p>
<p>而useRef,在多次更新中始终是同一个对象。这就是这句定义的解释：</p>
<blockquote>
<p>在组件的整个生命周期内持续存在</p>
</blockquote>
<p><strong>因此当有一个不涉及渲染的复杂对象需要维护时，用useRef就可以避免频繁更新导致创建该对象的性能消耗。</strong></p>
<h2 id="forwardRef和useImperativeHandle"><a href="#forwardRef和useImperativeHandle" class="headerlink" title="forwardRef和useImperativeHandle"></a>forwardRef和useImperativeHandle</h2><h3 id="forwardRef"><a href="#forwardRef" class="headerlink" title="forwardRef"></a>forwardRef</h3><blockquote>
<p><code>React.forwardRef</code> 会创建一个React组件，这个组件能够将其接受的 <a href="https://zh-hans.reactjs.org%2Fdocs%2Frefs-and-the-dom.html" title="https://zh-hans.reactjs.org/docs/refs-and-the-dom.html">ref</a> 属性转发到其组件树下的另一个组件中。</p>
</blockquote>
<p>这个api主要有两个场景：转发ref和对function component使用ref(其实本质上也是转发ref)。</p>
<p>所谓的“转发”，其实也就是让你封装的组件支持ref属性，并通过ref暴露这个组件中的某一个dom（不一定是该组件的根dom）</p>
<p>另外，function component无法使用ref（因为它并没有组件实例）,这时候就可以使用这个api进行转发</p>
<blockquote>
<p><strong>You may not use the <code>ref</code> attribute on function components</strong> because they don’t have instances.</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title class_">FancyButton</span> = <span class="title class_">React</span>.<span class="title function_">forwardRef</span>(<span class="function">(<span class="params">props, ref</span>) =&gt;</span> (  <span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">ref</span>=<span class="string">&#123;ref&#125;</span> <span class="attr">className</span>=<span class="string">&quot;FancyButton&quot;</span>&gt;</span>    &#123;props.children&#125;</span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line">));</span><br><span class="line"></span><br><span class="line"><span class="comment">// You can now get a ref directly to the DOM button:</span></span><br><span class="line"><span class="keyword">const</span> ref = <span class="title class_">React</span>.<span class="title function_">createRef</span>();</span><br><span class="line"><span class="language-xml"><span class="tag">&lt;<span class="name">FancyButton</span> <span class="attr">ref</span>=<span class="string">&#123;ref&#125;</span>&gt;</span>Click me!<span class="tag">&lt;/<span class="name">FancyButton</span>&gt;</span></span>;</span><br></pre></td></tr></table></figure>

<h3 id="useImperativeHandle"><a href="#useImperativeHandle" class="headerlink" title="useImperativeHandle"></a>useImperativeHandle</h3><p>这个api与forwardRef配合使用，能使暴露出去的ref对象，具有它定义的某些功能</p>
<blockquote>
<p><code>useImperativeHandle</code> 可以让你在使用 <code>ref</code> 时自定义暴露给父组件的实例值。在大多数情况下，应当避免使用 ref 这样的命令式代码。<code>useImperativeHandle</code> 应当与 <a href="https://zh-hans.reactjs.org%2Fdocs%2Freact-api.html%23reactforwardref" title="https://zh-hans.reactjs.org/docs/react-api.html#reactforwardref"><code>forwardRef</code></a> 一起使用：</p>
</blockquote>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">function FancyInput(props, ref) &#123;</span><br><span class="line">  const <span class="attr">inputRef</span> = useRef()<span class="comment">;</span></span><br><span class="line">  useImperativeHandle(ref, () =&gt; (&#123;</span><br><span class="line">    focus: () =&gt; &#123;</span><br><span class="line">      inputRef.current.focus()<span class="comment">;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;))<span class="comment">;</span></span><br><span class="line">  return &lt;input <span class="attr">ref</span>=&#123;inputRef&#125; ... /&gt;<span class="comment">;</span></span><br><span class="line">&#125;</span><br><span class="line"><span class="attr">FancyInput</span> = forwardRef(FancyInput)<span class="comment">;</span></span><br></pre></td></tr></table></figure>

<h3 id="实例：antd3在form外部提交"><a href="#实例：antd3在form外部提交" class="headerlink" title="实例：antd3在form外部提交"></a>实例：antd3在form外部提交</h3><p>Talk is cheap. 我们来看一个实例：</p>
<p>antd3中，form对象没有submit属性，因此想要在外部（比如弹窗）触发form的onSubmit，就需要结合<code>useImperativeHandle</code>与<code>useImperativeHandle</code></p>
<p>form: 通过useImperativeHandle暴露submit方法，该方法会直接调用onSubmit。</p>
<p>当然也可以对外暴露更多的api，比如beforeSubmit、afterSubmit、onError，以及form对象等等。</p>
<figure class="highlight ini"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"> const <span class="attr">Demo</span> = React.forwardRef((props: FormComponentProps, ref)=&gt;&#123;</span><br><span class="line">  const &#123;</span><br><span class="line">    getFieldDecorator,</span><br><span class="line">    validateFields,</span><br><span class="line">  &#125; = props.form<span class="comment">;</span></span><br><span class="line">  const <span class="attr">onSubmit</span> = (e?: FormEvent)=&gt;&#123;</span><br><span class="line">    e?.preventDefault()<span class="comment">;</span></span><br><span class="line">    validateFields((e, v) =&gt; &#123;&#125;)</span><br><span class="line">  &#125;</span><br><span class="line">  useImperativeHandle(ref,()=&gt;(&#123;</span><br><span class="line">    submit:onSubmit</span><br><span class="line">  &#125;))</span><br><span class="line">  return &lt;Form <span class="attr">onSubmit</span>=&#123;<span class="literal">on</span>Submit&#125;&gt;</span><br><span class="line">    &lt;Form.Item <span class="attr">label</span>=<span class="string">&quot;姓名&quot;</span>&gt;</span><br><span class="line">      &#123;getFieldDecorator(&#x27;name&#x27;,&#123;rules:<span class="section">[&#123;required:true,message:&#x27;请输入用户名&#x27;&#125;]</span>&#125;)(</span><br><span class="line">        &lt;Input <span class="attr">placeholder</span>=<span class="string">&quot;user name&quot;</span>/&gt;</span><br><span class="line">      )&#125;</span><br><span class="line">    &lt;/Form.Item&gt;</span><br><span class="line">    &lt;Form.Item <span class="attr">label</span>=<span class="string">&quot;地址&quot;</span>&gt;</span><br><span class="line">    &#123;getFieldDecorator(&#x27;address&#x27;)(</span><br><span class="line">        &lt;Input <span class="attr">placeholder</span>=<span class="string">&quot;user address&quot;</span>/&gt;</span><br><span class="line">      )&#125;</span><br><span class="line">    &lt;/Form.Item&gt;</span><br><span class="line">  &lt;/Form&gt;</span><br><span class="line"> &#125;)</span><br><span class="line"></span><br><span class="line">const <span class="attr">DemoForm</span> =  Form.create()(Demo)</span><br></pre></td></tr></table></figure>

<p>modal: 创建ref，并传入组件，因为这里被Form.create了，因此需要按照文档传入<code>wrappedComponentRef</code></p>
<p>当点击确认时，调用ref.current.submit，这样就触发了表单的校验。</p>
<figure class="highlight typescript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">DemoModal</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> ref = useRef&lt;<span class="built_in">any</span>&gt;()</span><br><span class="line">  <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">Modal</span> <span class="attr">title</span>=<span class="string">&quot;demo&quot;</span> <span class="attr">visible</span>=<span class="string">&#123;true&#125;</span> <span class="attr">onOk</span>=<span class="string">&#123;()</span>=&gt;</span>&#123;ref.current.submit()&#125;&#125;&gt;</span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;<span class="name">DemoForm</span> <span class="attr">wrappedComponentRef</span>=<span class="string">&#123;ref&#125;</span>&gt;</span><span class="tag">&lt;/<span class="name">DemoForm</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">  <span class="tag">&lt;/<span class="name">Modal</span>&gt;</span></span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>效果：</p>
<p><img src="./../imgs/c3e1ac10e91f4a249046400414dd795c.png" alt="image.png"></p>

        
      </div>

         
    </div>
    
     
  </div>
  
    
<nav id="article-nav">
  <a class="article-nav-btn left "
    
      href="/hexo-blog/2021/11/24/CSS%E5%87%BD%E6%95%B0%E5%A4%A7%E5%85%A8%EF%BC%88%E4%B8%80%EF%BC%89%EF%BC%9A%E8%BF%90%E7%AE%97%E3%80%81%E7%BD%91%E6%A0%BC%E5%92%8C%E4%BC%AA%E7%B1%BB/"
      title="CSS函数大全（一）：运算、网格和伪类"
     >
    <i class="fa-solid fa-angle-left"></i>
    <p class="title-text">
      
        CSS函数大全（一）：运算、网格和伪类
        
    </p>
  </a>
  <a class="article-nav-btn right "
    
      href="/hexo-blog/2021/11/22/Vue2%E6%BA%90%E7%A0%81%E8%A7%A3%E6%9E%90%EF%BC%9A%E4%BB%8EnextTick%E4%B8%8E%E5%BC%82%E6%AD%A5%E6%9B%B4%E6%96%B0%E8%AF%B4%E8%B5%B7/"
      title="Vue2源码解析：从nextTick与异步更新说起"
     >

    <p class="title-text">
      
        Vue2源码解析：从nextTick与异步更新说起
        
    </p>
    <i class="fa-solid fa-angle-right"></i>
  </a>
</nav>


  
</article>





    </div>
    <div id="footer-wrapper">
      <footer id="footer">
  
  <div id="footer-info" class="inner">
    
    &copy; 2024 Zachary<br>
    <!-- Powered by <a href="https://hexo.io/" target="_blank">Hexo</a> & Theme <a target="_blank" rel="noopener" href="https://github.com/saicaca/hexo-theme-vivia">Vivia</a> -->
      <a target="_blank" rel="noopener" href="https://beian.miit.gov.cn">苏ICP备20030005号-2</a>
  </div>
</footer>

    </div>
    <div class="back-to-top-wrapper">
    <button id="back-to-top-btn" class="back-to-top-btn hide" onclick="topFunction()">
        <i class="fa-solid fa-angle-up"></i>
    </button>
</div>

<script>
    function topFunction() {
        window.scroll({ top: 0, behavior: 'smooth' });
    }
    let btn = document.getElementById('back-to-top-btn');
    function scrollFunction() {
        if (document.body.scrollTop > 600 || document.documentElement.scrollTop > 600) {
            btn.classList.remove('hide')
        } else {
            btn.classList.add('hide')
        }
    }
    window.onscroll = function() {
        scrollFunction();
    }
</script>

  </div>
  <script src="/hexo-blog/js/light-dark-switch.js"></script>
</body>
</html>
